# -*- coding: utf-8 -*-
"""
Created on Tue May  3 19:54:57 2022

@author: Apple
"""

import os
import sys
from PyQt5.QtWidgets import (QAbstractItemView,QMainWindow,QWidget,QTableWidget,QHBoxLayout,QMessageBox,QApplication,QTableWidgetItem,QHeaderView)
from main_window import Ui_MainWindow
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
import pandas as pd
import numpy as np
import math
import matplotlib.pyplot as plt
import re

class MainWindow(QMainWindow):
    def __init__(self,parent=None):
        super(MainWindow,self).__init__(parent)
        self.ui = Ui_MainWindow()
        self.ui.setupUi(self)
        
        self.ui.actionopen.triggered.connect(self.openfile)
        self.ui.actionversion.triggered.connect(self.showversion)
        self.ui.btn1_2.clicked.connect(lambda:self.newrow(tw1))
        self.ui.btn2_2.clicked.connect(lambda:self.newrow(tw2))
        self.ui.btn1_3.clicked.connect(lambda:self.delrow(tw1))
        self.ui.btn2_3.clicked.connect(lambda:self.delrow(tw2))
        self.ui.btn1_4.clicked.connect(lambda:self.savedata(tw1))
        self.ui.btn2_4.clicked.connect(lambda:self.savedata(tw2))
        self.ui.btn1_5.clicked.connect(lambda:self.cleartable(1))
        self.ui.btn2_5.clicked.connect(lambda:self.cleartable(2))
        self.ui.btn3_2.clicked.connect(lambda:self.cleartable(3))
        self.ui.btn4_2.clicked.connect(lambda:self.cleartable(4))
        self.ui.btn5_2.clicked.connect(lambda:self.cleartable(5))
        self.ui.btnO3.clicked.connect(lambda:self.cleartable(6))
        self.ui.btn1_1.clicked.connect(lambda:self.read_data(1,tw1))
        self.ui.btn2_1.clicked.connect(lambda:self.read_data(2,tw2))
        self.ui.btn3_1.clicked.connect(lambda:self.read_data(3,tw3))
        self.ui.btn4_1.clicked.connect(lambda:self.read_data(4,tw4))
        self.ui.btn5_1.clicked.connect(lambda:self.read_data(5,tw5))
        self.ui.btn5_1.clicked.connect(lambda:self.read_data(5,tw5))
        self.ui.btnO1.clicked.connect(lambda:self.read_data(6,tw6))
        self.ui.btnE1.clicked.connect(self.savesettings)
        self.ui.btnE2.clicked.connect(self.printresult)
        self.ui.btnE3.clicked.connect(self.clearall)
        
        
        # 初始化表格1
        tw1 = self.ui.tableWidget1
        tw1.setRowCount(1)
        tw1.setColumnCount(12)
        tw1.setHorizontalHeaderLabels(['配送日期','站点代码','到站名称','罐号','油品代码','油品名称','升数（升）','数量（公斤）','油库代码','油库名称','重点站','配送优先级'])
        
        tw1.setEditTriggers(QTableWidget.CurrentChanged)
        for i in range(12):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tw1.setItem(0,i,newItem)
        
        # 初始化表格2
        tw2 = self.ui.tableWidget2
        tw2.setRowCount(1)
        tw2.setColumnCount(14)
        tw2.setHorizontalHeaderLabels(['车号','车辆装载品种','总升数','总仓数','第一仓','第二仓','第三仓','第四仓','所属车队','挂车','核定载质量','超限载质量','是否有高速公务卡','运输次数'])
        
        tw2.setEditTriggers(QTableWidget.CurrentChanged)
        for i in range(14):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tw2.setItem(0,i,newItem)
        
        tw3 = self.ui.tableWidget3
        tw4 = self.ui.tableWidget4
        tw5 = self.ui.tableWidget5
        tw6 = self.ui.tableWidget6
    
    # 读取excel文件
    def read_excel(self,file_name):
        
        with open(file_name,'rb') as f:
            df = pd.read_excel(file_name)
        f.close()
        return df
    
    # 导入数据
    def read_data(self,model,tw):
        
        if model == 1:
            file_name = r'基础数据/Order.xlsx'
            df = self.read_excel(file_name)
        elif model == 2:
            file_name = r'基础数据/Vehicle.xlsx'
            df = self.read_excel(file_name)
        elif model == 3:
            file_name = r'基础数据/dis_mat.xlsx'
            df = self.read_excel(file_name)
            df.set_index(df.columns[0], inplace=True)
        elif model == 4:
            file_name = r'基础数据/clu_mat.xlsx'
            df = self.read_excel(file_name)
            df.set_index(df.columns[0], inplace=True)
        elif model == 5:
            file_name = r'基础数据/per_mat.xlsx'
            df = self.read_excel(file_name)
            df.set_index(df.columns[0], inplace=True)
        elif model == 6:
            file_name = r'schme.xlsx'
            df = self.read_excel(file_name)
        
        c_title = df.columns.tolist()
        r_title = df.index.tolist()
        # print(c_title)
        # print(r_title)
        
        c_str = [str(i) for i in c_title]
        r_str = [str(i) for i in r_title]

        tw.clear()
        tw.setRowCount(len(r_title))
        tw.setColumnCount(len(c_title))
        for i,row in enumerate(r_title):
            for j,col in enumerate(c_title):
                newItem = QTableWidgetItem(str(df.loc[row][col]))
                newItem.setTextAlignment(Qt.AlignCenter)
                tw.setItem(i,j,newItem)
        
        tw.setHorizontalHeaderLabels(c_str)
        tw.setVerticalHeaderLabels(r_str)
        tw.setEditTriggers(QTableWidget.CurrentChanged)
    
    # 打开本地文件
    def openfile(self):
        path = os.getcwd() 
        os.startfile(path)
    
    # 展示当前版本
    def showversion(self):
        QMessageBox.about(self, '关于', '当前版本为 V1.0 ')
        
    # 新增一行
    def newrow(self,tw):
        tableWidget = tw
        numrow = tableWidget.rowCount()
        numcol = tableWidget.columnCount()
        tableWidget.insertRow(numrow)
        for i in range(numcol):
            newItem = QTableWidgetItem('')
            newItem.setTextAlignment(Qt.AlignCenter)
            tableWidget.setItem(numrow,i,newItem)
            
    # 删除一行
    def delrow(self,tw):

        tableWidget = tw
        numrow = tableWidget.rowCount()
        numcol = tableWidget.columnCount()
        if numrow == 1:
            tableWidget.removeRow(0)
            tableWidget.insertRow(0)
            for i in range(numcol):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tableWidget.setItem(0,i,newItem)            
        else:
            tableWidget.removeRow(numrow-1)
            
    # 保存当前输入
    def savedata(self,tw):
        tableWidget = tw
        numrow = tableWidget.rowCount()
        numcol = tableWidget.columnCount()
        listall = []
        for i in range(numrow):
            listcol = []
            for j in range(numcol):
                data = tableWidget.item(i,j).text()
                listcol.append(data)
                if data =='':
                    QMessageBox.about(self, '警告', '请输入完整数据')
                    return
                else:
                    listcol.append(data)
            listall.append(listcol)
        # print(listall)
        if tw == self.ui.tableWidget1:
            path = os.getcwd() + r'\test.csv'
        else:
            path = os.getcwd() + r'\test.csv'
        # print(path)
        test = pd.DataFrame(data = listall)
        test.to_csv(path,index=0)
        QMessageBox.about(self, '完成', '保存成功')
        
    # 清空表格内容
    def cleartable(self,model):
        
        if model == 1:
            title = ['配送日期','站点代码','到站名称','罐号','油品代码','油品名称','升数（升）','数量（公斤）','油库代码','油库名称','重点站','配送优先级']
            tw1 = self.ui.tableWidget1
            tw1.clear()
            tw1.setRowCount(1)
            tw1.setColumnCount(12)
            for i in range(12):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tw1.setItem(0,i,newItem)
            
            tw1.setHorizontalHeaderLabels(title)
            tw1.setEditTriggers(QTableWidget.CurrentChanged)
            
        elif model == 2:
            title = ['车号','车辆装载品种','总升数','总仓数','第一仓','第二仓','第三仓','第四仓','所属车队','挂车','核定载质量','超限载质量','是否有高速公务卡','运输次数']
            tw2 = self.ui.tableWidget2
            tw2.clear()
            tw2.setRowCount(1)
            tw2.setColumnCount(14)
            tw2.setEditTriggers(QTableWidget.CurrentChanged)
            for i in range(14):
                newItem = QTableWidgetItem('')
                newItem.setTextAlignment(Qt.AlignCenter)
                tw2.setItem(0,i,newItem)
            
            tw2.setHorizontalHeaderLabels(title)
            tw2.setEditTriggers(QTableWidget.CurrentChanged)
        
        elif model == 3:
            tw = self.ui.tableWidget3
            tw.clear()
            tw.setRowCount(0)
            tw.setColumnCount(0)
        
        elif model == 4:
            tw = self.ui.tableWidget4
            tw.clear()
            tw.setRowCount(0)
            tw.setColumnCount(0)
        
        elif model == 5:
            tw = self.ui.tableWidget5
            tw.clear()
            tw.setRowCount(0)
            tw.setColumnCount(0)
        
        elif model == 6:
            tw = self.ui.tableWidget6
            tw.clear()
            tw.setRowCount(0)
            tw.setColumnCount(0)
    
    # 保存参数设置        
    def savesettings(self):
        
        settings = []
        settings.append(self.ui.cost_1.text())
        settings.append(self.ui.cost_2.text())
        settings.append(self.ui.cost_3.text())
        settings.append(self.ui.cost_4.text())
        for i in range(4):
            data = settings[i]
            if data =='':
                QMessageBox.about(self, '警告', '请输入完整数据')
                return
        print(settings)
        path = os.getcwd() + '\\1.csv'
        print(path)
        path = path.replace('\\','/')
        test = pd.DataFrame(data = settings)
        test.to_csv(path,index=0)
        QMessageBox.about(self, '完成', '保存成功')
    
    def printresult(self):
        
        with open("scheme.txt", "r") as f:  # 打开文件
            data = f.read()
        self.ui.textEdit.setText(data)
    
    def clearall(self):
        self.ui.textEdit.clear()
        

if __name__=="__main__":
    app = QApplication(sys.argv)
    win = MainWindow()
    win.show()
    sys.exit(app.exec_())